﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Admin.RelationQuery
{
    public partial class RelationshipManageCtoC : BasePage
    {
        public RelationshipManageCtoC()
        {
            this.ModuleNo = Module.配送关系管理.ToString();
            this.PageOperateType = OperateType.配送关系审核.ToString();
        }
        IBLL_Distribution iDistribution = Factory.BLL_Distribution();
        IBLL_SelectRelation iselectRelation = Factory.BLL_SelectRelation();
        IBLL_Company IBC = Factory.BLL_Company();

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                BindArea();
                BangdinGvRelaion();
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            BangdinGvRelaion();
        }
        /// <summary>
        /// 绑定事件
        /// </summary>
        private void BangdinGvRelaion()
        {
            string strWhere = GetCondition();

            strWhere += "  order by companyid_tb,productname,areaid,ProcurecatalogID,CompanyID_PS ";

            int totalCount = 0;
            DataTable dt = iselectRelation.GetSelectRelationToConfirm(strWhere, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            GvRelaion.DataSource = dt;
            GvRelaion.DataBind();
            AspNetPager1.RecordCount = totalCount;
        }

        protected string GetCondition()
        {
            string strWhere = " ";

            #region 查询条件
            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtGoodsName.Text.Trim())))
            {
                strWhere += " and GoodsName like '%" + HZ.Fun2.CheckString(this.txtGoodsName.Text.Trim()) + "%'";
            }
            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtProcureCatalogID.Text.Trim())))
            {
                strWhere += " and ProcureCatalogID like '%" + HZ.Fun2.CheckString(this.txtProcureCatalogID.Text.Trim().ToUpper()) + "%'";
            }
            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtOutlookc.Text.Trim())))
            {
                strWhere += " and Outlookc like '%" + HZ.Fun2.CheckString(this.txtOutlookc.Text.Trim()) + "%'";
            }
            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtpinyincode.Text.Trim()))) //拼音码
            {//'%'||UPPER('{1}')||'%'
                strWhere += " and UPPER(PinyinCode) like '%'||UPPER('" + HZ.Fun2.CheckString(txtpinyincode.Text.Trim().ToUpper()) + "')||'%'";
            }
            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtMaterial.Text.Trim())))
            {
                strWhere += " and Material like '%" + HZ.Fun2.CheckString(this.txtMaterial.Text.Trim()) + "%'";
            }
            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtCompanyName_TB.Text.Trim())))
            {
                strWhere += " and CompanyName_TB like '%" + HZ.Fun2.CheckString(this.txtCompanyName_TB.Text.Trim()) + "%'";
            }
            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtUnit.Text.Trim())))
            {
                strWhere += " and Unit like '%" + HZ.Fun2.CheckString(this.txtUnit.Text.Trim()) + "%'";
            }

            strWhere += " and ProjectID ='" + this.ddlProjectid.SelectedValue + "'";
            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtCompanyName_PS.Text.Trim())))
            {
                strWhere += " and CompanyName_PS like '%" + HZ.Fun2.CheckString(this.txtCompanyName_PS.Text.Trim()) + "%'";
            }
            if (string.IsNullOrEmpty(this.DllStatusType.SelectedValue))
            {
                strWhere += "  and status <> '-1' ";
            }
            else
            {
                strWhere += "  and status='" + DllStatusType.SelectedItem.Text + "' ";
            }
            if (string.IsNullOrEmpty(this.ddlCity.SelectedValue))
            {
            }
            else
            {
                strWhere += "  and Areaid='" + ddlCity.SelectedValue + "' ";
            }

            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtCompanyID_PS.Text.Trim())))
            {
                strWhere += " and CompanyID_PS='" + HZ.Fun2.CheckString(this.txtCompanyID_PS.Text.Trim()) + "'";
            }
            if (string.IsNullOrEmpty(this.DllAuditStatusType.SelectedValue))
            {

            }
            else
            {
                strWhere += "  and AuditStatus='" + DllAuditStatusType.SelectedItem.Text + "' ";
            }
            if (!string.IsNullOrEmpty(HZ.Fun2.CheckString(this.txtAuditer.Text.Trim())))
            {
                strWhere += " and Auditer='" + HZ.Fun2.CheckString(this.txtAuditer.Text.Trim()) + "'";
            }

            if (string.IsNullOrEmpty(this.dllRequestdelete.SelectedValue))
            {

            }
            else
            {
                strWhere += "  and Requestdelete='" + dllRequestdelete.SelectedItem.Text + "' ";
            }
            #endregion

            return strWhere;
        }

        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            BangdinGvRelaion();
        }

        /// <summary>
        /// 将给定的url加上script 实现页面跳转
        /// 针对button 的 onclintclick 新窗口打开
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected string OpenURLScript(string str)
        {
            int index = str.IndexOf("?");
            //给url加returnUrl,值为当前页面的Url
            if (index != -1)
            {
                str += "&" + Constants.QUERYSTRING_RETURN_URL + "=" + Page.Request.RawUrl;
            }
            else
            {
                str += "?" + Constants.QUERYSTRING_RETURN_URL + "=" + Page.Request.RawUrl;
            }
            string strScript = "if(!this.disabled){window.open('" + str + "');} return false;";
            return strScript;
        }


        protected void btnExport_Click(object sender, EventArgs e)
        {

            string strWhere = GetCondition();

            strWhere += " order by companyid_tb,productname ";

            int totalCount = 0;

            DataTable dt = iselectRelation.GetSelectRelationToConfirm(strWhere, 1, 0, out totalCount);

            HZ.Excel.ExcelHelper.ExportDataForWeb(dt, GvRelaion);
        }
        /// <summary>
        /// 备注：此处亦清除配送企业和医疗机构的配送关系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Del(object sender, EventArgs e)
        {
            HZ.Web.HzLinkButton btn = sender as HZ.Web.HzLinkButton;
            string str = btn.CommandArgument.ToString();
            string[] array = str.Split(',');

            HZ.DrugTrade.Model.SelectRelation aAreaDistribution = new HZ.DrugTrade.Model.SelectRelation();
            aAreaDistribution.ProcureCatalogID = array[0];
            aAreaDistribution.CompanyID_PS = array[1];
            aAreaDistribution.AreaID = array[2];
            aAreaDistribution.Auditer = CurrentAccount.GetUser().UserID;
            if (iselectRelation.DeleteSelectRelationByAdmin(aAreaDistribution) == 1)
            {
                HZ.Web.WebUtil.Alert("删除成功！", this);
                BangdinGvRelaion();
            }
            else
            {
                HZ.Web.WebUtil.Alert("删除失败！", this);
            }

        }

        /// <summary>
        /// 绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GvRelaion_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HZ.Web.HzLinkButton btn = e.Row.FindControl("lbtnDel") as HZ.Web.HzLinkButton;
                HZ.DrugTrade.Model.SelectRelation item = e.Row.DataItem as HZ.DrugTrade.Model.SelectRelation;
                btn.CommandArgument = string.Format("{2},{1},{0}", this.GvRelaion.DataKeys[e.Row.RowIndex].Values["AreaID"], this.GvRelaion.DataKeys[e.Row.RowIndex].Values["CompanyID_PS"], this.GvRelaion.DataKeys[e.Row.RowIndex].Values["ProcureCatalogID"]);
                //if ( Constants.CURRENT_DEPLOY_AREAID!= CurrentAccount.GetUser( ).Org.Area.AreaID )   //不是省级的单位不允许删除关系
                //{
                //    btn.Enabled=false;
                //}
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected bool getCheckstatus(string str, int status)
        {
            if (status == 1)
            {
                if (str.Equals("未确定") || str.Equals("已拒绝"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            if (status == 2)
            {
                if (str.Equals("未确定") || str.Equals("已同意"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            if (status == 3)
            {
                if (str.Equals("可配送"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hzbtnAgree_Click(object sender, EventArgs e)
        {
            updateStatusBatch(1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hzbtnDeny_Click(object sender, EventArgs e)
        {
            updateStatusBatch(2);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="status"></param>
        protected void updateStatusBatch(int status)
        {
            IList<Model.SelectRelation> lst = new List<Model.SelectRelation>();

            //遍历列表的所有行
            for (int _index = 0; _index < GvRelaion.Rows.Count; _index++)
            {
                CheckBox ckb = ((CheckBox)GvRelaion.Rows[_index].FindControl("checkbox1"));
                if (ckb.Checked && ckb.Enabled)
                {
                    HZ.DrugTrade.Model.SelectRelation aAreaDistribution = new HZ.DrugTrade.Model.SelectRelation();
                    aAreaDistribution.ProcureCatalogID = this.GvRelaion.DataKeys[_index].Values["ProcureCatalogID"].ToString();
                    aAreaDistribution.CompanyID_PS = this.GvRelaion.DataKeys[_index].Values["CompanyID_PS"].ToString();
                    aAreaDistribution.AreaID = this.GvRelaion.DataKeys[_index].Values["AreaID"].ToString();
                    //aAreaDistribution.Status = status;
                    aAreaDistribution.CompanyID_TB = this.GvRelaion.DataKeys[_index].Values["CompanyID_TB"].ToString();

                    aAreaDistribution.Auditer = CurrentAccount.GetUser().UserID;
                    aAreaDistribution.AuditStatus = status;

                    if (status == 1)
                    {
                        aAreaDistribution.AuditReason = "";
                    }
                    else
                    {
                        string selval = "";
                        for (int i = 0; i < ckblistReason.Items.Count; i++)
                        {
                            if (ckblistReason.Items[i].Selected)
                            {
                                selval += ckblistReason.Items[i].Value + "";
                            }
                        }
                        if (string.IsNullOrEmpty(this.txtReason.Text.Trim()) == false)
                        {
                            selval += HZ.Fun2.CheckString(this.txtReason.Text.Trim()) + "；";
                        }
                        if (string.IsNullOrEmpty(selval.Trim()) == false)
                        {
                            selval = selval.Substring(0, selval.Length - 1) + "。";
                        }
                        if (selval == "")
                        {
                            HZ.Web.WebUtil.Alert("请填写未审核通过的原因！", this);
                            return;
                        }
                        else
                        {
                            aAreaDistribution.AuditReason = selval;
                        }
                    }

                    lst.Add(aAreaDistribution);

                }
            }
            if (lst.Count > 0)
            {
                if (iselectRelation.UpdateSelectRelationAuditStatus(lst) == 1)
                {
                    //PageInfo("操作成功！", Request.RawUrl);
                    HZ.Web.WebUtil.Alert("操作成功！", this);
                }
                else
                {
                    //PageError("操作失败！", Request.RawUrl);
                    HZ.Web.WebUtil.Alert("操作失败！", this);
                }
                BangdinGvRelaion();
            }
            else
            {
                HZ.Web.WebUtil.Alert("至少选择一条记录！", this);
            }
        }
        /// <summary>
        /// 绑定地区
        /// </summary>
        public void BindArea()
        {
            IBLL_Area ia = Factory.BLL_Area();
            IList<Area> lstArea = new List<Area>();
            string userAreaId = CurrentAccount.GetUser().Org.Area.AreaID;
            //判断用户所属地区，如果用户是省级的 则可以列出全部区域
            if (userAreaId == CurrentAccount.GetCurrentDeployArea().AreaID)
            {
                lstArea = ia.GetAllCity(userAreaId);
                foreach (Area area in lstArea)
                {
                    ListItem ddlitem = new ListItem();
                    ddlitem.Text = area.AreaName;
                    ddlitem.Value = area.AreaID;
                    ddlCity.Items.Add(ddlitem);
                }

                ListItem a = new ListItem();
                a.Text = "全部";
                a.Value = "";
                ddlCity.Items.Insert(0, a);

            }
            else
            {
                lstArea.Add(ia.GetArea(userAreaId));
                foreach (Area area in lstArea)
                {
                    ListItem ddlitem = new ListItem();
                    ddlitem.Text = area.AreaName;
                    ddlitem.Value = area.AreaID;
                    ddlCity.Items.Add(ddlitem);
                }
                ///省级以下的单位不允许删除关系


            }
            //绑定数据源
            //如果有当前省的编号，则增加省直属 
            //同时地区获取值的要设置 

        }
    }
}
